import axios from "axios";
import { ElNotification, ElMessage } from "element-plus";
import { tansParams } from "./tools.ts";
import errorCode from "./errorCode.ts";

const service = axios.create({
  baseURL: "",
  timeout: 10000,
});
/**
 * @description: 请求拦截
 */
service.interceptors.request.use(
  (config) => {
    // get请求映射params参数
    if (config.method === "get" && config.params) {
      let url = config.url + "?" + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  },
);
/**
 * @description: 响应拦截
 */
service.interceptors.response.use(
  async (res) => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode.default;
    if (code === 401) {
      return await Promise.reject("无效的会话，或者会话已过期，请重新登录。");
    } else if (code === 500) {
      ElMessage({ message: msg, type: "error" });
      return await Promise.reject(new Error(msg));
    } else if (code === 601) {
      ElMessage({ message: msg, type: "warning" });
      return await Promise.reject(new Error(msg));
    } else if (code !== 200) {
      ElNotification.error({ title: "系统错误请联系管理员" });
      return await Promise.reject("error");
    }
    return await Promise.resolve(res.data);
  },
  async (error) => {
    let { message } = error;
    if (message === "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    ElMessage({ message, type: "error", duration: 3 * 1000 });
    return await Promise.reject(error);
  },
);

export default service;
